package org.groupg.systemcore.utilities.io;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class IOSteamUtils {


    /**
     * 根据文件与字符集以及字段间、行间隔符对数据进行分割
     *
     * @param file       文件内容
     * @param charset    字符集
     * @param fieldSplit 字段间隔符
     * @param lineSplit  行间隔符
     * @return 一个文件内容字段
     * @throws IOException 文件有问题的相关异常
     */
    public synchronized static Stream<String[]> lines(File file, Charset charset, String fieldSplit, String lineSplit) throws IOException {

        Iterator<String[]> iter = new Iterator<>() {
            String[] nextLine = null;
            StringBuilder s = new StringBuilder();

            final FileReader reader = new FileReader(file, charset);
            final BufferedReader br = new BufferedReader(reader);

            @Override
            public boolean hasNext() {
                if (nextLine != null) {
                    return true;
                } else {
                    try {
                        int i;
                        while ((i = br.read()) != -1) {
                            s.append((char) i);
                            if (s.toString().length() > lineSplit.length() && s.toString().endsWith(lineSplit)) {
                                s.setLength(s.toString().lastIndexOf(lineSplit));
                                nextLine = (s.toString().split(fieldSplit));
                                s = new StringBuilder();
                                break;
                            }
                        }
                        return (nextLine != null);
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                }
            }

            @Override
            public String[] next() {
                if (nextLine != null || hasNext()) {
                    String[] line = nextLine;
                    nextLine = null;
                    return line;
                } else {
                    throw new NoSuchElementException();
                }
            }
        };
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
                iter, Spliterator.ORDERED | Spliterator.NONNULL), false);
    }
}
